#include "readthread.h"
#include <QDebug>
#include <QTextStream>
#include <QFile>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>

ReadThread::ReadThread(int fd, QObject *parent)
    : QThread(parent), m_fd(fd)
{
}

void ReadThread::run()
{
    char buffer[1024]; // 定义buffer数组

    QFile file;
    if (!file.open(m_fd, QIODevice::ReadOnly | QIODevice::Unbuffered)) {
        qDebug() << "❌ QFile 打开失败:" << file.errorString();
        emit connectionClosed(); // 触发断开信号
        return;
    }

    QTextStream in(&file);
    while (!isInterruptionRequested()) {
        QString line = in.readLine();
        if (line.isNull()) {
            int bytesRead = file.read(reinterpret_cast<char*>(buffer), sizeof(buffer));
            if (bytesRead == 0) {
                qDebug() << "读取结束";
                emit connectionClosed(); // 通知主线程连接已关闭
                break;
            }
            continue;
        }
        emit newData(line);
    }

    file.close();
    emit connectionClosed(); // 触发断开信号
}



